import type { CarouselProps } from './types.ts'
import React, { useEffect, useState } from 'react'
import './carousel.scss'

const Carousel: React.FC<CarouselProps> = (
  {
    images = [],
    // 可配置的播放间隔，默认3秒
    interval = 3000,
  },
) => {
  // 如果没有图片则返回提示
  if (images.length === 0) {
    return <div></div>
  }
  // 如果只有一张图片，则直接显示
  if (images.length === 1) {
    return (
      <div className="carousel">
        <img src={images[0]} alt="Single slide" className="carousel-image" />
      </div>
    )
  }
  // 添加复制的第一张和最后一张图片以实现无缝切换
  const extendedImages = [images[images.length - 1], ...images, images[0]]
  // 初始显示第二张图片
  const [currentIndex, setCurrentIndex] = useState(1)
  // 切换到下一张图片
  const goToNext = () => {
    setCurrentIndex(prevIndex => prevIndex + 1)
  }
  // 自动播放逻辑：在组件挂载时启动定时器
  useEffect(() => {
    const timer = setInterval(() => {
      goToNext()
    }, interval)
    // 清除定时器，避免内存泄漏
    return () => clearInterval(timer)
  }, [interval])
  useEffect(() => {
    // 当切换到最后一张复制的图片时，设置为第二张图片
    if (currentIndex === extendedImages.length - 1) {
      setTimeout(() => {
        // 跳转到第二张
        setCurrentIndex(1)
      }, 1000)
    }
  }, [currentIndex])
  // 计算当前显示的图像索引
  const displayIndex = (currentIndex > images.length ? (currentIndex - images.length) : currentIndex)
  return (
    <div className="carousel">
      <div
        className="carousel-track"
        style={{
          transform: `translateX(-${currentIndex * 100}%)`,
          // 只有在平滑切换时才应用过渡
          transition: currentIndex === 1 ? 'none' : 'transform 1s ease-in-out',
        }}
      >
        {extendedImages.map((image, index) => (
          <img
            key={index}
            src={image}
            alt={`Slide ${index}`}
            className="carousel-image"
          />
        ))}
      </div>
      <div className="carousel-counter">
        <span>{displayIndex}</span>
        <span>/</span>
        <span>{images.length}</span>
      </div>
    </div>
  )
}

export default Carousel
